package com.xinghen.common.util;

import org.apache.commons.collections.CollectionUtils;

import java.sql.*;
import java.util.*;

/**
 * @author xinghen
 * @ClassName: JdbcUtils
 * @Package: com.xinghen.util
 * @Description JDBC工具类
 * @create 2017-12-05 16:11
 */
public class JdbcUtils {

    private Connection connection;

    private PreparedStatement preparedStatement;

    private ResultSet resultSet;

    /**
     * 初始化数据库连接
     *
     * @param driver
     * @param url
     * @param username
     * @param password
     */
    public JdbcUtils(String driver, String url, String username, String password) {
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
            System.out.println("数据库连接成功");
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询多交记录
     *
     * @param sql
     * @param params
     * @return
     * @throws SQLException
     */
    public List<Map<String, Object>> selectByParam(String sql, List<String> params) throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();
        int index = 1;
        preparedStatement = connection.prepareStatement(sql);
        if (CollectionUtils.isNotEmpty(params)) {
            for (String param : params) {
                preparedStatement.setObject(index++, param);
            }
        }
        resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (resultSet.next()) {
            Map<String, Object> map = new HashMap<>(columnCount);
            for (int i = 0; i < columnCount; i++) {
                String columnName = metaData.getColumnName(i + 1);
                Object columnValue = resultSet.getObject(columnName);
                columnValue = null == columnValue ? "" : columnValue;
                map.put(columnName, columnValue);
            }
            list.add(map);
        }
        return list;
    }

    /**
     * 释放资源
     */
    public void release() {
        try {
            if (!Objects.isNull(resultSet)) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (!Objects.isNull(preparedStatement)) {
                preparedStatement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (!Objects.isNull(connection)) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
